import React, { useContext, useEffect, useRef, useState, useImperativeHandle } from 'react';
import { Button, Form, Input, Table, Modal, message } from 'antd';
import { apiShopSalesReturnForceRefund } from '@/request/orderManagement'
import TheUpload from "@/components/TheUpload";
import TheImage from '@/components/TheImage'
const { TextArea } = Input
const formRef = React.createRef()

const EditableContext = React.createContext(null);
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};
const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);
  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };
  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({
        ...record,
        ...values,
      });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };
  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }
  return <td {...restProps}>{childNode}</td>;
};

const Refund = React.forwardRef((props, ref) => {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [dataSource, setDataSource] = useState([]);
  const [tableData, setTableData] = useState([])
  const [selectedRowDatas, setSelectedRowDatas] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [step, setStep] = useState(1)
  const [shopOrderId, setShopOrderId] = useState()
  const defaultColumns = [
    {
      title: '商品信息',
      width: 400,
      render: (text, record, index) => {
        return (
          <div style={{ display: 'flex', alignItems: 'center' }} >
            <TheImage src={record.goodsImage} width={50} />
            <span style={{ margin: '0 10px' }} >{record.goodsName}</span>
            {
              record.giftId !== '0' &&
              <div className='gift'>赠</div>
            }
          </div>
        )
      },
    },
    {
      title: '规格',
      dataIndex: 'sku',
      key: 'sku',
      render: (text) => text || '',
    },
    {
      title: '物料ID',
      dataIndex: 'materialId',
      key: 'materialId',
      width: 200,

      render: (text) => text || '',
    },
    {
      title: '商品单价',
      dataIndex: 'orderPrice',
      key: 'orderPrice',
      render: (text) => <React.$price price={text || 0} />,
    },
    {
      title: '数量',
      dataIndex: 'orderProductCount',
      key: 'orderProductCount',
      width: 70,

      render: (text) => text || 0,
    },
    {
      title: '总计',
      dataIndex: 'orderPriceTotal',
      key: 'orderPriceTotal',
      render: (text) => <React.$price price={text || 0} />,
    },
  ];
  const [loading, setLoading] = useState(false)

  useImperativeHandle(ref, () => ({
    open: () => {
      setDataSource(props.dataSource)
      setTableData(props.dataSource)
      setShopOrderId(props.shopOrderId)
      setIsModalOpen(true)
    }
  }));

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };
  const onSelectChange = (newSelectedRowKeys) => {
    console.log(newSelectedRowKeys, props.dataSource);
    const selectedRow = props.dataSource.filter(item => newSelectedRowKeys.includes(item.key))
    setSelectedRowDatas(selectedRow)
    setSelectedRowKeys(newSelectedRowKeys)
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    getCheckboxProps: (record) => {
      console.log(record);
      return ({

        disabled: ['1', '2', '3', '9'].includes(record.salesStatus),
        name: record.salesStatus,
      })
    }
  };
  const handleSave = (row) => {

  };
  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });

  const submit = (str) => {
    switch (str) {
      case 'cancel':
        formRef.current && formRef.current.setFieldsValue({
          reason: '',
          returnDocuments: ''
        })
        setSelectedRowDatas([])
        setSelectedRowKeys([])
        setStep(1)
        setIsModalOpen(false)
        break;
      case 'next':
        if (selectedRowDatas && selectedRowDatas.length > 0) {
          setStep(2)
          setTableData(selectedRowDatas)
        } else {
          message.warn('请选择要操作退款的商品！');
        }
        break;
      case 'prev':
        setStep(1)
        setTableData(dataSource)
        break;
      case 'ok':
        console.log(formRef);
        formRef.current.validateFields().then((value) => {
          apiShopSalesReturnForceRefund({
            reason: value.reason,
            returnDocuments: value.returnDocuments,
            shopOrderDetailIds: selectedRowKeys,
            shopOrderId: shopOrderId
          }).then(res => {
            if (res.code === 0) {
              message.success('操作成功！');
              formRef.current && formRef.current.setFieldsValue({
                reason: '',
                returnDocuments: ''
              })
              setSelectedRowDatas([])
              setSelectedRowKeys([])
              setStep(1)
              setIsModalOpen(false)
              props.refresh()

            }
          })

        }).catch(err => {
          // message.warn(err.codeMessage);
        })

        break;
      default:
        break;
    }

  }
  const getFileResult = (value) => {

    if (value) {

      const arr = value.map(item => {
        if (item.response && item.response.code === 0) {
          return item.response.data
        }
      })
      formRef.current.setFieldsValue({
        returnDocuments: arr.join(',')
      })
    }
  };
  const handleCancel = () => {
    setIsModalOpen(false)
  }
  return (
    <Modal visible={isModalOpen} onCancel={() => submit('cancel')} footer={
      step === 1 ?
        [
          <Button key="cancel" onClick={() => submit('cancel')}>
            取消
          </Button>,
          <Button key="next" type="primary" onClick={() => submit('next')}>
            下一步
          </Button>
        ] : [
          <Button key="prev" onClick={() => submit('prev')}>
            上一步
          </Button>,
          <Button
            type="primary" loading={loading}
            onClick={() => submit('ok')}
          >
            完成
          </Button>]} width={1200}>
      <Table style={{ margin: '30px 20px 0px', fontSize: 12 }}
        scroll={{
          y: 400,
        }}
        components={components}
        rowClassName={() => 'editable-row'}
        rowSelection={step === 1 ? rowSelection : null}
        bordered
        pagination={false}
        dataSource={tableData}
        columns={columns}
        summary={(pageData) => {
          let totalOrderPriceTotal = 0
          let totalOrderProductCount = 0
          pageData.forEach(({ orderPriceTotal, orderProductCount }) => {
            totalOrderPriceTotal += orderPriceTotal || 0
            totalOrderProductCount += orderProductCount || 0
          })
          return (

            <Table.Summary fixed>
              <Table.Summary.Row >
                <Table.Summary.Cell colSpan={step === 1 ? 7 : 6}>
                  <div style={{ textAlign: 'center' }}>
                    {`共${totalOrderProductCount}件商品，总计`}
                    <React.$price price={totalOrderPriceTotal || 0} />元
                  </div>
                </Table.Summary.Cell>
              </Table.Summary.Row>
            </Table.Summary>

          )
        }}
      />
      <>
        {
          step === 1 ? null :
            <Form ref={formRef} labelCol={{ span: 2 }} style={{ marginTop: 20 }}>
              <Form.Item label={'退款原因'} name="reason" rules={[{ required: true }]}>
                <TextArea rows={4} maxLength={120} showCount />
              </Form.Item>
              <Form.Item label={'其他凭证'} name="returnDocuments" rules={[{ required: false }]}>
                <TheUpload
                  len={3}
                  getFileResult={getFileResult}
                />
              </Form.Item>
            </Form>
        }
      </>
    </Modal>
  );
})



export default Refund;